<template>
	<view class="start-game">
		<!-- #ifndef H5 -->
		<statusBar></statusBar>
		<!-- #endif -->
		<gameInfo :num="gamePlayerNum" :status="gameProcessStatus" :date="$utils.formatDate(Date.now())" />
		<seat seatTitle="主持人分配座位" seatTip="主持人可点击座位手动分配,或踢出玩家" :seatList="gameSeatList" />
		<view class="dm-control">
			<view class="control-btn">
				<button class="mini-btn" type="warn" size="mini" @click="clearPlayerSeat">强制离开</button>
			</view>
			<view class="control-btn">
				<button class="mini-btn" type="primary" size="mini" @click="subStartGame">开始游戏</button>
			</view>
		</view>
		<view>
			<!-- 强制离开提示窗 -->
			<uni-popup ref="alertClearPlayerDialog" type="dialog">
				<uni-popup-dialog type="warn" title="玩家座位重置" :content="clearPlayerInfo"
					@confirm="dialogConfirmClearPlayer" @close="cancelClearPlayer"></uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 开始游戏信息弹窗 -->
			<uni-popup ref="alertConfirmPlayerDialog" type="dialog">
				<uni-popup-dialog type="warn" title="开始游戏" :content="playerStandByInfo" @confirm="dialogConfirmStartGame"></uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 玩家就座/录入信息情况提示窗 -->
			<uni-popup ref="alertPlayerStandByDialog" type="dialog">
				<uni-popup-dialog type="warn" title="玩家座位重置" :content="clearPlayerInfo"
					@confirm="dialogConfirmClearPlayer"></uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 操作结果提示窗 -->
			<uni-popup ref="resultMessage" type="message">
				<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
			</uni-popup>
		</view>

	</view>
</template>

<script>
	import statusBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-status-bar";
	import gameInfo from '@/components/gameinfo.vue'
	import seat from '@/components/seat.vue'
	import { GAME_STAGE } from '@/common/utils'
	import {querygamedetailbydm,endgame,startgame,quitgame} from "@/common/api"
	import {mapState,mapMutations,mapGetters,mapActions} from "@/store/helper/dm"
	export default {
		components: {
			statusBar,
			gameInfo,
			seat
		},
		onLoad(){
			this.updatePlayerStatus()
			console.log(this.gameProcessStatus)
		},
		onShow(){
			// #ifdef MP-WEIXIN
			//每隔5秒查询更新一次游戏信息
			let that = this
			this.timer = setInterval(function(){
				that.updatePlayerStatus();
				console.log(1);
				clearInterval(this.timer)
				},5000)
			if (this.gameStatus!= "init" ) {clearInterval(this.timer)}
			// #endif
		},
		onUnload(){
		    clearInterval(this.timer);
		},
		onHide(){
		    clearInterval(this.timer);
		},
		data() {
			return {
				timer:null,
				msgType: '',
				messageText: '',
				clearPlayerInfo: "",
				playerStandByInfo: "",
				selectedSeatNum: 0,
				selectedUserId: "",
				selectedUserName: "",
				unSubRolePlayers: [],
				sitDownSeat: [],
				returnMsg: "",
			}
		},
		computed: {
			...mapState([
				"user",
				"currentGameDTO",
				"currentGameID",
				"currentGameRoleListConfirm",
				"gameStatus",
				"currentGameRoleParams",
				"currentChoiceSeatNum"
			]),
			...mapGetters([
				"gameProcessStatus",
				"gamePlayerNum",
				"gameSeatList"
			]),
		},
		methods: {
			async updatePlayerStatus(){
				//更新玩家座位信息
				const {data,code,message} = await querygamedetailbydm({"code":this.currentGameID})
				if (data.code === "200") {
					this.setCurrentGameDTO(data.data.game)
					this.msgType = 'success'
					this.messageText = '刷新玩家准备信息成功'
					this.$refs.resultMessage.open()
				} else {
					this.msgType = 'error'
					this.messageText = `刷新玩家准备信息失败:` + data.message
					this.$refs.resultMessage.open()
				}
				//清除定时器防抖
				// clearInterval(this.timer)
			},
			clearPlayerSeat() {
				//判断是否已有玩家就座
				if(Object.keys(this.currentGameDTO).length >0){
					let tmp = this.currentGameDTO.players.filter(n => {
						return n.seatNumber === this.currentChoiceSeatNum
					})
					//判断当前点击的座位是否有人就座
					if(tmp.length !=0){
						this.selectedUserId = tmp[0].user.id
						this.selectedUserName = tmp[0].user.nickname
						this.clearPlayerInfo = "请确认是否踢出该玩家座位？" + "\n\n玩家微信昵称：" + this.selectedUserName + "\n 当前选中座位：" + this
							.currentChoiceSeatNum
					} else{
						this.clearPlayerInfo="当前座位为空或未选中玩家，\n请确认后再进行操作"
					}
				} else {
					this.clearPlayerInfo="当前未有玩家进入，请与玩家联系或等待座位信息刷新"
					this.$refs.alertClearPlayerDialog.open()
					return
				}
				this.$refs.alertClearPlayerDialog.open()
			},
			cancelClearPlayer(){
				this.currentChoiceSeatNum(0)
			},
			async dialogConfirmClearPlayer() {
				//提交清空玩家命令，这里的接口暂时写player的
				const {data,code,message} = await quitgame({
					"gameCode": this.currentGameID,
					"seatNumber": this.currentChoiceSeatNum,
					"userId": this.selectedUserId
				})
				if (data.code === "200") {
					this.currentChoiceSeatNum = "0",
					this.selectedUserId = ""
					this.msgType = 'success'
					this.messageText = `清空玩家座位信息成功:`
					this.$refs.resultMessage.open()
				} else{
					this.msgType = 'error'
					this.messageText = `清空玩家座位信息失败:` + data.message
					this.$refs.resultMessage.open()
				}
			},
			async subStartGame() {
				for (let i = 0; i < this.currentGameDTO.players.length; i++) {
				//轮询当前玩家是否录入身份
				this.sitDownSeat.push(this.currentGameDTO.players[i].seatNumber)
				if (this.currentGameDTO.players[i].gameRole.code === null) {
						this.unSubRolePlayers.push(this.currentGameDTO.players[i].user.nickname)
					}
				}
				if (this.unSubRolePlayers.length===0 ) {
					this.playerStandByInfo = "玩家已准备完毕，请点击确认开始游戏"
				} else {
					this.playerStandByInfo = "本轮游戏有如下玩家未准备，请确认" + "\n\n 未录入身份的玩家：" + this.unSubRolePlayers
				}
				this.$refs.alertConfirmPlayerDialog.open()
			},
			async dialogConfirmStartGame() {
				if (this.gameStatus==='init') {
					const {data,code,message} = await startgame({"code": this.currentGameID})
					if (data.code === "200") {
						clearInterval(this.timer)
						this.setCurrentGameDTO(data.data.game)
						this.setGameStatus(data.data.processStatus)
						this.setCurrentGameID(data.data.code)
						this.createFirstNight()
						uni.redirectTo({
							url: 'pages/view/dm/processing-game'
						})
					} else {
						this.msgType = 'error'
						this.messageText = `开始游戏失败:` + data.message
						this.$refs.resultMessage.open()
					}
				} else {
					return
				}
			},
			async createFirstNight(){
				const {code,data,message} = await this.createcurrentround({
					"code": this.currentGameID
				})
				if (data.code === "200") {
					this.setGameStageCode(data.gameProcessingInfo.curStageCode)
					//回合历史设置本地缓存
					uni.setStorageSync('GAME_STAGE',data.gameProcessingInfo.curStageCode)
					//当前选中项为当前回合
					this.msgType = 'success'
					this.messageText = `创建首夜成功`
					this.$refs.resultMessage.open()
					}else{
						this.msgType = 'error'
						this.messageText = data.message
						this.$refs.resultMessage.open()
					}
			},
			...mapMutations([
				"setGameStatus",
				"setCurrentGameDTO",
				"setGameStageCode",
				"currentChoiceSeatNum"
			]),
			...mapActions([
				"clearCurrentGame"
			])
		}
	}
</script>

<style lang="scss" scoped>
	.dm-control {
		display: flex;
		justify-content: center;
		align-items: center;
		flex: 1;
	}

	.control-btn {
		margin: 20px 10px;
	}

	.uni-section {
		height: 600rpx;
	}

	.uni-card {
		height: 450rpx;
	}
</style>
